/* eslint-disable default-case */
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import {
  handleList,
  handleDicList,
  startHandle,
  originCircle,
  handleStartList,
  insSendInfor,
  addContactInfor,
  insAdd,
  insAddCheck,
  insSubmitToRun,
  insfundDetail,
  insToDealComplete,
  insertProbFdbk,
  getProBaseList,
  cancelProbFlag,
  insaddHdlRemark,
  insHdlRemark,
  insCancelToDeal,
  addRefundInfor,
  socialUpdateDetail,
  socialUpdate,
  getEmpNameList,
  handleEsList,
  insGrants,
  getServiceDictList,
  checkSocialInfor,
  getRefundInfor,
  uploadFile,
  uploadFileGrant,
} from '@/services/socialmanage';
import { getMatList } from '@/services/socialservice';
import { getUploadProgress } from '@/services/careermange';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'handle';

export default {
  namespace,
  state: {
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
    },
    activeKey: '1',
    expandForm: false, // 渲染表单
    issWayArr: [{ itemCode: '1', itemName: '现场发放' }, { itemCode: '2', itemName: '快递邮寄' }], // 原件发放方式
    requiredFlag: false, // 是否必填
    selectedRowKeys: [],
    sendData: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
    },
    formFieldsValue: {},
    dicData: [], // 服务类型字典值
    flagData: [], // 是否有返款字典
    selectedRows: [],
    selectedKeys: [],
    alertObjList: [],
    nameContent: '',
    nameTitle: '',
    tabList: [
      { itemCode: '1', itemName: '待办理' },
      { itemCode: '2', itemName: '办理中' },
      { itemCode: '3', itemName: '已办理' },
      { itemCode: '5', itemName: '问题人员' },
      { itemCode: '4', itemName: '已取消' },
    ],
    toDealList: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insSerHdl: {},
      matlist: [],
      originalRemark: {},
      selectedRows: [],
      remmarkList: [],
      insRefundInfo: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 10,
        },
      },
    },
    contactList: [],
    detail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insSerHdl: {},
      originalRemark: {},
      insRefundInfo: [],
      matlist: [],
      remarklist: [],
    },
    updatedetail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insCardHdl: {},
      elementArr: {},
      matFileDictItem: {},
    },
    proBaseList: {},
    proFbList: [],
    proVno: 0,
    detailHdl: [],
    empNameSelect: [],
    empNameList: [],
    elementArr: [],
    matFileDictItem: [],
    serviceDictList: [],
    messageData: {},
    refundObj: {},
    batchQuery: {
      // // 批量上传数据
      areaId: null,
      contType: null,
      progressPercent: 0,
    },
    resultInfo: {
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
      errorUrl: '/esApi/insSerHdl/insBatchIssueErrData', // 下载错误信息地址
    },
    progressPercent: 0,
    showProgress: false,
    currentStep: 0,
    downloadParams: {},
  },

  effects: {
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 获取列表 运行
    *fetchList({ payload }, { call, put }) {
      const response = yield call(handleList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 员工
    *fetchEsList({ payload }, { call, put }) {
      const response = yield call(handleEsList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    // 获取派单信息
    *fetchSendInfor({ payload }, { call, put }) {
      const response = yield call(insSendInfor, payload); // 请求
      if (response.success) {
        yield put({
          type: 'sendList', // 处理后台返回数据
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 新增
    addList: [
      function*({ payload, callback }, { call }) {
        const response = yield call(insAdd, payload);
        callback(response);
      },
      { type: 'throttle', ms: 10000 },
    ],
    *addCheckList({ payload, callback }, { call }) {
      const response = yield call(insAddCheck, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchDicList({ payload }, { call, put }) {
      const response = yield call(handleDicList, payload);
      if (response.success) {
        yield put({
          type: 'dicList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchUpdateDetail({ payload }, { call, put }) {
      const response = yield call(socialUpdateDetail, payload);
      if (response.success) {
        yield put({
          type: 'getUpdateDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
        yield put(routerRedux.goBack());
      }
    },
    updateList: [
      function*({ payload, callback }, { call }) {
        const response = yield call(socialUpdate, payload);
        if (response.success) {
          callback(response.success);
        } else {
          message.warning(response.message || '服务端错误');
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    *updateToDealDetial({ payload }, { call, put }) {
      const response = yield call(handleStartList, payload);
      if (response.success) {
        yield put({
          type: 'getToDealDetial',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *getRefund({ payload }, { call, put }) {
      const response = yield call(getRefundInfor, payload);
      if (response.success) {
        yield put({
          type: 'getRefundInfor',
          payload: {
            data: response.data,
          },
        });
      } else {
        yield put({
          type: 'getRefundInfor',
          payload: {
            data: {},
          },
        });
      }
    },

    // 原件流转
    *circle({ payload, callback }, { call }) {
      const response = yield call(originCircle, payload);
      if (callback) callback(response);
    },

    // 社保服务办理问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(insertProbFdbk, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },
    // 获取问题人员详情
    *fetchProBaseList({ payload }, { call, put }) {
      const response = yield call(getProBaseList, payload);
      if (response.success) {
        yield put({
          type: 'getProBaseList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 反馈并取消
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(cancelProbFlag, payload);
      callback(response);
    },
    // 开始办理
    *startHandles({ payload, callback }, { call }) {
      const response = yield call(startHandle, payload);
      if (response.success) {
        callback(response.success);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *updateGrants({ payload, callback }, { call }) {
      const response = yield call(insGrants, payload);
      callback(response);
    },
    // 联系
    *addContact({ payload }, { call, put }) {
      const response = yield call(addContactInfor, payload);
      if (response.success) {
        yield put({
          type: 'getContact',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *submitToRun({ payload, callback }, { call }) {
      const response = yield call(insSubmitToRun, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *addRefund({ payload, callback }, { call }) {
      const response = yield call(addRefundInfor, payload);
      callback(response);
    },
    *fetchDetail({ payload }, { call, put }) {
      const response = yield call(insfundDetail, payload);
      if (response.success) {
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *updateToDealComplete({ payload, callback }, { call }) {
      const response = yield call(insToDealComplete, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *addHdlRemark({ payload, callback }, { call }) {
      const response = yield call(insaddHdlRemark, payload);
      if (callback) callback(response);
    },
    *addHdlRemarkDel({ payload, callback }, { call, put }) {
      const response = yield call(insaddHdlRemark, payload);
      if (response.success) {
        callback(response);
        const resAgin = yield call(insHdlRemark, { busiId: payload.busiId });
        if (resAgin.success) {
          yield put({
            type: 'updateData',
            payload: resAgin.data,
          });
        } else {
          message.warning(resAgin.message);
        }
      }
    },
    // 服务办理--办理备注
    *detailHdlRemark({ payload }, { call, put }) {
      const response = yield call(insHdlRemark, payload);
      if (response.success) {
        yield put({
          type: 'getHdlRemark',
          payload: response.data,
        });
      }
    },
    *cancelToDeal({ payload, callback }, { call }) {
      const response = yield call(insCancelToDeal, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message);
      }
    },
    *fetchMatList({ payload }, { call, put }) {
      const response = yield call(getMatList, payload);
      if (response.success) {
        yield put({
          type: 'getMatList',
          payload: response.data,
        });
        return response;
      }
      return message.warning(response.message);
    },
    // 获取模糊查询员工姓名列表
    *fetchEmpNameList({ payload }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'getEmpNameList',
            payload: Array.isArray(response.data) ? response.data : [],
          });
        }
        if (!response.data.length) {
          message.warning('当前所输的不存在，请检查 ');
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchEmpNoList({ payload, callback }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        if (response.data.length) {
          yield put({
            type: 'getEmpNoList',
            payload: Array.isArray(response.data) ? response.data : [],
          });
          callback(false);
        } else {
          callback(true);
          message.warning('当前所输的证件号不存在，请检查 ');
        }
      } else {
        callback(true);
        message.warning(response.message || '服务端错误');
      }
    },

    // 查询服务类型列表
    *fetchServiceDictList({ payload }, { call, put }) {
      const response = yield call(getServiceDictList, payload);
      if (response.success) {
        yield put({
          type: 'getServiceDictList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *checkSocial({ payload, callback }, { call, put }) {
      const response = yield call(checkSocialInfor, payload);
      if (response.rspCode === '101') {
        callback(true);
        yield put({
          type: 'messageData',
          payload: response.message,
        });
      } else {
        callback(false);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        try {
          let api;
          if (payload.type === 'batch') {
            api = uploadFile;
          }
          if (payload.type === 'grant') {
            api = uploadFileGrant;
          }
          const response = yield call(api, payload.formData);
          if (response.success) {
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.handle);
      let { showProgress, resultInfo, currentStep } = state;

      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batNo: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    updateData(state, { payload }) {
      const remarklist = payload;
      return {
        ...state,
        detail: { ...state.detail, remarklist },
      };
    },
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: { list, pagination: { total: data.totalCount, current: currentPage, pageSize } },
      };
    },
    sendList(state, { payload }) {
      return {
        ...state,
        sendData: payload,
      };
    },
    dicList(
      state,
      {
        payload: { data },
      }
    ) {
      const tempArr = [];
      data.ALRT_OBJ.forEach(item => {
        tempArr.push({ label: item.itemName, value: item.itemCode });
      });
      return {
        ...state,
        dicData: data.INS_SERVICE_TYPE,
        flagData: data.YES_NO_FLAG,
        alertObjList: tempArr,
      };
    },

    selectRow(state, { payload }) {
      return {
        ...state,
        selectedRows: payload.selectedRows,
        selectedKeys: payload.selectedKeys,
      };
    },
    messageData(state, { payload }) {
      return {
        ...state,
        messageData: payload,
      };
    },
    getRefundInfor(state, { payload }) {
      return {
        ...state,
        refundObj: payload.data,
      };
    },
    toggleVisible(state, { payload }) {
      return {
        ...state,
        circleVisible: !payload,
      };
    },
    originCircle(state, { payload }) {
      return {
        ...state,
        circleVisible: !payload,
      };
    },

    refunds(state, { payload }) {
      return {
        ...state,
        updatedetail: {
          ...state.updatedetail,
          insCardHdl: { ...state.updatedetail.insCardHdl, ...payload },
        },
      };
    },

    getToDealDetial(state, { payload }) {
      const {
        empSendInfoVo,
        empBaseInfoVo,
        insSerHdl,
        matlist,
        origInalRemark,
        insRefundInfo,
        selectedRows,
        remmarkList,
      } = payload.data;
      return {
        ...state,
        toDealList: {
          empSendInfoVo,
          empBaseInfoVo,
          insSerHdl,
          matlist,
          origInalRemark,
          insRefundInfo,
          selectedRows,
          remmarkList,
        },
      };
    },
    getContact(state, { payload }) {
      return {
        ...state,
        contactList: Array.isArray(payload) ? payload : [],
      };
    },

    // 获取详情
    getDetail(state, { payload }) {
      return {
        ...state,
        detail: payload,
      };
    },
    getProBaseList(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbks,
      };
    },
    getHdlRemark(state, { payload }) {
      return {
        ...state,
        detailHdl: Array.isArray(payload) ? payload : [],
      };
    },
    getUpdateDetail(state, { payload }) {
      const elementArr = [];
      const maGpages = payload.serMatPkgVo.maGpages ? payload.serMatPkgVo.maGpages : [];
      if (maGpages.length) {
        maGpages.forEach(item => {
          if (item.maGpDetails.length) {
            item.maGpDetails.forEach(d => {
              const obj = {};
              if (d.children) {
                obj.children = d.children;
                obj.children.map(c => {
                  const newC = c;
                  if (Number(c.inpType) === 11) {
                    newC.areaValue = c.inpVal ? c.inpVal.split(',') : undefined;
                    newC.name = d.inpValName;
                  }
                  return true;
                });
              }
              if (Number(d.inpType) === 9) {
                const fileArr = d.inpVal ? d.inpVal.split(',') : [];
                const fileList = [];
                Object.keys(fileArr).forEach(key => {
                  const tempObj = {
                    uid: fileArr[key].split('|')[0],
                    name: fileArr[key].split('|')[1],
                    status: 'done',
                  };
                  fileList.push(tempObj);
                });
                obj.fileList = fileList;
              }
              obj.reqFlag = d.reqFlag; // 是否必填
              obj.matName = d.matName;
              obj.inpType = d.inpType;
              obj.matId = d.matId;
              obj.pageDetailId = d.pageDetailId;
              obj.dictItems = d.nmDictItem;
              if (d.inpVal) {
                obj.inpVal = d.inpVal;
              } else {
                obj.inpVal = d.dftVal;
              }
              if (Number(d.inpType) === 9) {
                const fileArr = d.inpVal ? d.inpVal.split(',') : [];
                const fileList = [];
                Object.keys(fileArr).forEach(key => {
                  const tempObj = {
                    uid: fileArr[key].split('|')[0],
                    name: fileArr[key].split('|')[1],
                  };
                  fileList.push(tempObj);
                });
                obj.fileList = fileList;
              }
              elementArr.push(obj);
            });
          }
        });
      }
      const { matFileDictItem } = payload.serMatPkgVo;
      const { empBaseInfoVo } = payload;
      const { empSendInfoVo } = payload;
      const insCardHdl = payload.insSerHdl;
      Object.keys(insCardHdl).forEach(key => {
        if (key === 'copyFile') {
          insCardHdl[key] = insCardHdl[key].split(',');
        } else if (key === 'masterFile') {
          insCardHdl[key] = insCardHdl[key].split(',');
        }
      });
      elementArr.forEach((element, i) => {
        if (element.children && element.children.length) {
          element.children.forEach(item => {
            if (Number(item.judgeLogicCode) === Number(element.dftVal)) {
              elementArr.splice(i + 1, 0, item);
            }
          });
        }
      });

      return {
        ...state,
        coltFlag: payload.serMatPkgVo.coltFlag,
        updatedetail: { elementArr, matFileDictItem, empBaseInfoVo, empSendInfoVo, insCardHdl },
      };
    },
    // 获取服务类型列表
    getServiceDictList(state, { payload }) {
      return {
        ...state,
        serviceDictList: payload,
      };
    },
    getMatList(state, { payload }) {
      const elementArr = [];
      const maGpages = payload.maGpages ? payload.maGpages : [];
      if (maGpages.length) {
        maGpages.forEach(item => {
          if (item.maGpDetails.length) {
            item.maGpDetails.forEach(d => {
              const obj = {};
              if (d.children) {
                obj.children = d.children;
              }
              obj.dftVal = d.dftVal; // 默认值
              obj.reqFlag = d.reqFlag; // 是否必填
              obj.matName = d.matName;
              obj.matId = d.matId;
              obj.inpType = d.inpType;
              obj.pageDetailId = d.pageDetailId;
              obj.dictItems = d.nmDictItem;
              obj.inpVal = d.inpVal; // 默认值
              elementArr.push(obj);
            });
          }
        });
      }
      const { matFileDictItem } = payload;

      elementArr.forEach((element, i) => {
        if (element.children && element.children.length) {
          element.children.forEach(item => {
            if (Number(item.judgeLogicCode) === Number(element.dftVal)) {
              elementArr.splice(i + 1, 0, item);
            }
          });
        }
      });

      return {
        ...state,
        ...payload,
        elementArr,
        matFileDictItem,
      };
    },
    matInfor(state, { payload }) {
      let { elementArr } = payload;
      const { element } = payload;
      if (String(element.inpType) === '4') {
        let index;
        elementArr.forEach((elem, i) => {
          if (Number(elem.pageDetailId) === Number(element.pageDetailId)) {
            index = i;
          }
        });
        if (element.children && element.children.length) {
          element.children.forEach(item => {
            if (Number(item.judgeLogicCode) === Number(element.inpVal)) {
              elementArr.splice(index + 1, 0, item);
            } else {
              elementArr = elementArr.filter(ele => ele.matId !== item.matId);
            }
          });
        }
      }
      return {
        ...state,
        elementArr,
      };
    },
    getEmpNameList(state, { payload }) {
      const empData = Array.isArray(payload) ? payload : [];

      return {
        ...state,
        empNameList: empData,
        empNameSelect: empData,
      };
    },
    fetchEmpName(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    getEmpNoList(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 清空
    clearEmpName(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 更新state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
